/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package connection;

import java.net.*;
import java.io.*;
import overlay.*;
import protocollo.*;
import java.util.concurrent.*;


/**
 *
 * @author fabrizioscenna
 */
public class Server extends Thread{

    private ServerSocket serverSocket;
    private int id;
    private Socket socket;
    private ObjectInputStream objIn;
    private int port;
    private LinkedBlockingQueue coda;



    public Server(LinkedBlockingQueue coda, int backlog) throws IOException{
      
        serverSocket = new ServerSocket(0, backlog);
        port = serverSocket.getLocalPort();
        this.coda = coda;
        
   
        System.out.println("ID " + id + " server creato ");
    }

    public int getPort(){
        return port;
    }

    public void run(){

        System.out.println("ID " + id + " server in attesa di connessione");

        try{

            while(true){
                socket = serverSocket.accept();
                ClientHandler ch = new ClientHandler(socket);
                ch.start();
            
                


            }
            }catch(Exception e){
                System.out.println("ID " + id + "server errore in run" );
                closeSocket();
                System.exit(-1);
            }

        }

    public void closeSocket(){
         try{
             socket.close();
         } catch(Exception e){
             System.out.println("ID " + id + " server errore in chiusura");
         }

     }



    public class ClientHandler extends Thread{
        
        private Socket socket;
        
        private ObjectInputStream objIn ;
        
        public ClientHandler(Socket socket) throws Exception{
            this.socket = socket;
         
            objIn = new ObjectInputStream(socket.getInputStream());
            System.out.println(socket);
            System.out.println(" server ha accettato il client");
        
        }
        
        public void run(){
            
                
          
            while(true){
            try{
                Pacchetto p = (Pacchetto)objIn.readObject();
                if(p!=null)  coda.put(p);
                     }catch(Exception e){
                System.out.println("Errore in client handler ");
             }   
                
           
            }
        }
    }



}